//
//  homeTableViewController.swift
//  我的微博练习
//
//  Created by zhangguo on 15/10/8.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit

class homeTableViewController: BaseTableViewController {

    var statuss: [Status]?{
        didSet {
            //刷新数据
           tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //如果用户没有登录，返回访客视图
        if !UserAccount.userLogon {
            visitorView?.setUpViewInfor(true, imageName: "visitordiscover_feed_image_smallicon", message: "关注一些人，回这里看看有什么惊喜")
            
            return
        }
        
        //注册通知  selectPictures: 有参数必须在要加冒号“：”必须！！！！！
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectPictures:", name: GFStatusCellSelectPictureNotification, object: nil)
        
        perparTableView()
        loadData()
    }
    
    //选中照片监听方法
    //通知对象
     @objc func selectPictures(n: NSNotification){
    
        //获取参数，从自定义通知获取参数，一定要检查参数值
        
        guard let urls = n.userInfo![GFStatusSelectPictureURLKey] as?[NSURL] else {
            
            print("url数组不存在")
            return
            
        }
        
        guard let indexPath = n.userInfo![GFStatusSelectPictureIndexKey] as? NSIndexPath else {
            
            print("indexPath，没有")
            return
        }
        //价差图像视图
        guard let picView = n.object as? StatusPictureView else {
            print("图像不存在")
            return
        }
        
        //记录属性
        pictureView = picView
        // 设置转场动画的iconview
        presentIconView.sd_setImageWithURL(urls[indexPath.item])
        //起始位置图片索引
        presentIndexPath = indexPath
        
        
        //提供给照片查看器的索引，应该是整数
        let vc = PhotoBrowearViewController(urls: urls, index: indexPath.item)
        //自定义转场动画
        vc.transitioningDelegate = self
        //指定Modal转场动画的模式    Custom是自定义的专场动画
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    deinit {
        //关闭通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    //准备表格视图
    private func perparTableView(){
    
        tableView.registerClass(StatusPictureNormelCell.self, forCellReuseIdentifier: StatusCellIdentifier.NormalCell.rawValue)
          tableView.registerClass(StatusFowrdCell.self, forCellReuseIdentifier: StatusCellIdentifier.ForwardCell.rawValue)
        //预估行高
        tableView.estimatedRowHeight = 300

        //添加下拉方法 ,下拉控件是60高度
        refreshControl = GFUIRefreshControl()
        //添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)

    }
    
    //上拉刷新标记
    private var pullupRefreshFlag = false
    //加载数据
     func loadData(){
        //开始动画
        refreshControl?.beginRefreshing()

        var since_id = statuss?.first?.id ?? 0
        var max_id = 0
        
        //判断是否上拉刷新
        if pullupRefreshFlag {
            since_id = 0
            max_id = statuss?.last?.id ?? 0
            
        }
        //加载数据
        //防止循环引用，加入[weak self]
        Status.loadStatus(since_id,max_id:max_id) {(datalist, error) -> () in
            
            //结束刷新视图
            self.refreshControl?.endRefreshing()

            if error != nil{
                print(error)
                return
            }
        
           let count = datalist?.count ?? 0
            print("刷新到\(count) 条数据")
            
            //只有下拉刷新有需要提示
            if since_id > 0 {
                self.showPulldownTip(count)
            }
            //如果没数据，直接返回
            if count == 0 {
                return
            }
            //做下拉刷新
            if since_id > 0 {
                
                self.statuss = datalist! + self.statuss!
            
            }else if max_id > 0{
                
                self.statuss! += datalist!
                //复位上啦刷新标记,下次可用
                self.pullupRefreshFlag = false
                
            }else{
                self.statuss = datalist
            }
        }
    }
    
    //显示下拉刷新的数据条数
    private func showPulldownTip(count:Int) {
        
        //判断是否在刷新，如果在刷新，就返回
        print(tipLabel.layer.animationKeys())
        if tipLabel.layer.animationForKey("position") != nil {
            print("正在刷新，请稍候...")
            return
        }
        
      //定义标签文字
        tipLabel.text = count == 0 ? "没有微博" : "刷新到\(count)微博  "
        
        //动画
        let rect = tipLabel.frame
        
        UIView.animateWithDuration(1.0, animations: { () -> Void in

            //自动翻转动画
            UIView.setAnimationRepeatAutoreverses(true)
            self.tipLabel.frame = CGRectOffset(rect, 0, 3 * rect.height)
            }) { (_) -> Void in
                
                self.tipLabel.frame = rect
        }
    }
    
    //数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuss?.count ?? 0
    }
    
    //每次显示cell的时候，调用此方法
    //如果indexPath == 微博数组的总数减一，表示显示最后一行
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        //根据微博类型，选取不同的ID 
        let status = statuss![indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status), forIndexPath: indexPath) as! StatusCell
        
        //判断indexPath的数值
        if indexPath.row == (statuss?.count)! - 1 {
            //设置上啦标记
            pullupRefreshFlag = true
            //刷新数据
            loadData()
        }
        
        cell.statuss = statuss![indexPath.row]
      tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        return cell
    }
    
  //返回行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
     
        //判断模型中，是否已经缓存了行高
        //1,获取模型
        let status = statuss![indexPath.row]
        if let h = status.rowHeight {
            return h
        }
        //2 获取cell
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status)) as! StatusCell
            
        //3 记录并且返回计算的行高
        status.rowHeight = cell.rowHeight(status)
       
        //返回计算的行高
        return status.rowHeight!
    }
    
    private lazy var tipLabel: UILabel = {
        //定义标签
        let h:CGFloat = 44
        let label = UILabel(frame: CGRect(x: 0, y:-2 * h, width: self.view.bounds.width, height: h))
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        label.textColor = UIColor.whiteColor()
        
        //将label 添加到nav
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    }()
    //是否是 modal展现的标记
    private var ispresent = false
    //转场动画过程中的图像视图
    private lazy var presentIconView: UIImageView = {
     let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
    //转成选中的图片 collectionView， 计算起始位置和目标位置
    private var pictureView:StatusPictureView?
    
    //转场动画起始的图片索引
    private var presentIndexPath:NSIndexPath?
    
}

//转场动画协议
extension homeTableViewController:UIViewControllerTransitioningDelegate {
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        ispresent = true
        return self
    }
    
    //返回提供接触动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        ispresent = false
        return self
    }
}
//自定义转场动画
extension homeTableViewController: UIViewControllerAnimatedTransitioning {
    //自定义转场动画时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
        
    }
    //专场动画的元素和效果
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        
        print(fromVC)
        print(toVC)
        
        if ispresent {
        //展现动画
        let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
        //将动画的图像添加到目标视图中
        transitionContext.containerView()?.addSubview(presentIconView)
            
        //指定图像视图的起始位置
            let fromRect = pictureView!.cellScreenFrame(presentIndexPath!)
            let toRect = pictureView!.cellForScreenFrame(presentIndexPath!)
            
            presentIconView.frame = fromRect

//        toView.alpha = 0
    
    UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            
           self.presentIconView.frame = toRect
            
            }) { (_) -> Void in
                //删除动画的图像视图
                self.presentIconView.removeFromSuperview()
                //添加目标视图
                transitionContext.containerView()?.addSubview(toView)
                
                //动画结束后，一定要执行，如果不执行，系统会一直等下去，无法进行后面的操作
                transitionContext.completeTransition(true)
            }
            return
        }
        //解除转场
        //照片视图
            let fromeVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as?PhotoBrowearViewController
            let iv = fromeVC!.currentImageView()
        
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        
        iv.center = fromView.center
        iv.alpha = fromView.alpha
        iv.transform = CGAffineTransformScale(iv.transform, fromView.transform.a, fromView.transform.a)
        
        
            fromView.removeFromSuperview()
        
        transitionContext.containerView()?.addSubview(iv)
        
        let rect = pictureView!.cellScreenFrame((fromeVC?.currentImageIndex())!)
        
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                iv.frame = rect
                }, completion: { (_) -> Void in
                    
                   iv.removeFromSuperview()
                    //接触转场动画时，会把容器视图以及内部的内容一起销毁
                    transitionContext.completeTransition(true)
        })
    }
}

